<template>
  <div class="upload-img">
    <div class="change-images">
      <draggable v-model="uploadList" :animation="dargAnimation" draggable=".product-img" @change="handleDraggableChange" :disabled="maxNum <= 1">
        <div v-for="(item, index) in uploadList" :key="index" class="product-img">
          <img :src="item.url" />
          <div class="edit-box">
            <i class="el-icon-search" @click="handlePictureCardPreview(item)" />
            <i class="el-icon-delete" @click="handleRemove(index)" />
          </div>
        </div>
        <div class="addProImg" v-show="isUpload">
          <el-upload
            ref="upload"
            :action="baseUrl"
            list-type="picture-card"
            :on-success="handleImageSuccess"
            :multiple="multiple"
            accept=".jpg,.jpeg,.png,.gif"
            :before-upload="beforeUpload"
            :limit="maxNum"
            :on-exceed="onExceed"
            :show-file-list="false"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </div>
      </draggable>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { toStorage } from '@/utils'
export default {
  name: 'imgUpload',
  components: { draggable },
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    maxSize: {
      type: Number,
      default: 2048
    },
    dargAnimation: {
      type: Number,
      default: 200
    },
    maxNum: {
      type: Number,
      default: 1
    },
    value: {
      default: ''
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      isUpload: true,
      isWatch: true,
      baseUrl: process.env.VUE_APP_BASE_API + '/upload',
      uploadList: []
    };
  },
  mounted () {
    if (this.isWatch) {
      this.handleImgValue(this.value)
    }
  },
  methods: {
    beforeUpload (file) {
      if (!this.validImgUpload(file, this.maxSize)) {
        return false
      }
      return true
    },
    validImgUpload (file, size) {
      size = +size || 2048
      const isSizeOut = file.size / 1024 > size
      if (isSizeOut) {
        this.$message.error('上传图片大小不能超过' + toStorage(size * 1024))
      }
      return !isSizeOut
    },
    handleRemove(index) {
      this.uploadList.splice(index, 1)
      if (this.maxNum == 1) {
        this.$emit('input', '')
        this.isUpload = true
      } else {
        this.handleImgs(this.uploadList)
      }
      this.syncElUpload()
    },
    syncElUpload () {
      this.$refs.upload.uploadFiles = this.uploadList.map((v, i) => {
        return {
          name: 'pic' + i,
          url: v.url,
          status: 'success',
          uid: new Date().getTime()
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleImageSuccess(res, file) {
      file.url = res.data.url
      file.filesize = res.data.size
      this.uploadList.push({ url: file.url })
      if (this.maxNum == 1) {
        this.$emit('input', file.url)
        this.isUpload = false
      } else {
        this.handleImgs(this.uploadList)
      }
    },
    handleImgs (fileList) {
      let imgs = []
      if (fileList.length > 0) {
        for (let i = 0; i < fileList.length; i++) {
          imgs.push(fileList[i].url)
        }
      }
      this.$emit('input', imgs)
    },
    handleDraggableChange () {
      this.handleImgs(this.uploadList)
    },
    onExceed () {
      this.$refs.upload.abort()
      this.$message.warning(`最多只能上传 ${this.maxNum} 个文件`)
    },
    handleImgValue (value) {
      this.isWatch = false
      let defaultList = []
      if (this.maxNum == 1 && value) {
        defaultList.push({ url: value })
      } else if (this.maxNum > 1) {
        for (let k in value) {
          if (value[k]) {
            defaultList.push({
              url: value[k]
            })
          }
        }
      }
      if (this.maxNum === 1) {
        this.isUpload = defaultList.length > 0 ? false : true
      }
      this.uploadList = defaultList
      this.syncElUpload()
    }
  },
  watch: {
    value (val) {
      if (this.isWatch) {
        this.handleImgValue(val)
      }
    }
  }
}
</script>

<style lang="scss">
.upload-img .change-images {
  padding: 15px;
  text-align: left;
  height: auto;
  .product-img {
    position: relative;
    width: 100px;
    display: inline-block;
    vertical-align: top;
    margin: 0 5px 10px 5px;
    border-radius: 3px;
    text-align: center;
    height: 100px;
    cursor: grab;
    border: 1px solid #efefef;
    &:active {
      cursor: grabbing;
    }
    &:before {
      content: "";
      display: inline-block;
      vertical-align: middle;
      height: 100%;
    }
    img,
    video {
      display: inline-block;
      vertical-align: middle;
      max-width: 100%;
      max-height: 100%;
    }
    .edit-box {
      position: absolute;
      z-index: 9;
      background: rgba(0,0,0,.5);
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      text-align: center;
      justify-content: center;
      align-items: center;
      display: none;
      i {
        position: relative;
        display: inline-block;
        font-size: 20px;
        color: #fff;
        margin: 0 5px;
        cursor: pointer;
        opacity: 0.8;
        &:hover {
          opacity: 1;
        }
      }
    }
    &:hover {
      .edit-box {
        display: flex;
      }
    }
  }
  .addProImg {
    display: inline-block;
    vertical-align: top;
    position: relative;
    border-radius: 3px;
    border: 1px dashed #ddd;
    width: 98px;
    height: 98px;
    text-align: center;
    margin: 0 5px;
    cursor: pointer;
    .el-upload--picture-card {
      width: 98px;
      height: 98px;
      line-height: 98px;
    }
  }
}
</style>
